﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Downloader.Framework.Core;
using Downloader.Framework.Extensions;
using Newtonsoft.Json;

namespace Downloader.Framework.Queries
{
    public class Sorter
    {
        public string Property
        {
            get;
            set;

        }
        public string Direction { get; set; }
    }
   public class QueryParamsBase
    {

        public int? Start { get; set; }
        public int? Limit { get; set; }


        private string _orderby;
        /// <summary>
        /// 例如" UserName desc,CreateTime asc"
        /// </summary>
        public string OrderBy
        {
            get
            {
                if (string.IsNullOrEmpty(_orderby))
                {
                    if (Sort.NotNullAndEmpty())
                    {
                        try
                        {
                            var sorters = JsonConvert.DeserializeObject<IList<Sorter>>(Sort);
                            string str = sorters.Aggregate("", (current, sorter) => current + string.Format(",{0} {1}", sorter.Property, sorter.Direction.IsNullOrEmpty() ? "asc" : sorter.Direction));
                            if (str.Length > 0)
                                _orderby = str.Substring(1);
                        }
                        catch
                        {
                            return string.Format("{0} {1}", Sort, Dir.IsNullOrEmpty() ? "asc" : Dir);

                        }

                    }
                }
                return _orderby;
            }
            set { _orderby = value; }
        }

        public string Sort { get; set; }
        public string Dir { get; set; }


        public virtual IQueryable<T> Get<T, TId>(IQueryable<T> queryable) where T : EntityBase<TId>
        {

            if (OrderBy.NotNullAndEmpty())
                return queryable.OrderUsingSortExpression(OrderBy);


            return queryable.OrderByDescending(c => c.Id);
        }
        public virtual IQueryable<T> Get<T>(IQueryable<T> queryable) where T : EntityBase
        {
            return Get<T, int>(queryable);
        }

        public virtual string ToQueryString()
        {
            //var tp = this.GetType();
            return string.Empty;

        }
    }
}
